package com.toilet.easyvideofx.controller;

import atlantafx.base.controls.RingProgressIndicator;
import atlantafx.base.controls.Tile;
import atlantafx.base.layout.InputGroup;
import com.toilet.easyvideofx.compent.RequestComponent;
import com.toilet.easyvideofx.constant.StringConstant;
import com.toilet.easyvideofx.constant.StyleConstant;
import com.toilet.easyvideofx.constant.SystemConstant;
import com.toilet.easyvideofx.domain.Sysconfig;
import com.toilet.easyvideofx.manager.FileManager;
import com.toilet.easyvideofx.model.FileListModel;
import com.toilet.easyvideofx.service.SysConfigService;
import com.toilet.easyvideofx.service.impl.SysConfigServiceImpl;
import com.toilet.easyvideofx.util.IPUtil;
import com.toilet.easyvideofx.util.QRCodeGenerator;
import com.toilet.easyvideofx.view.DownloadViewModel;
import com.toilet.easyvideofx.view.View;
import io.helidon.config.Config;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import org.kordamp.ikonli.antdesignicons.AntDesignIconsOutlined;
import org.kordamp.ikonli.javafx.FontIcon;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.util.*;

public class MainController implements Initializable {
    public AnchorPane mainPane;
    public ToolBar toolBar;
    public Button userButton;
    public Button relaxButton;
    public Button setButton;
    public Pane showPane;
    public Button uploadButton;
    /**
     * 下载列表
     */
    public ListView<DownloadViewModel> downloadListView;
    /**
     * 查看我的文件
     */
    public Button viewMyFile;
    /**
     * H5上传
     */
    public Button h5Upload;
    /**
     * 文件管理
     */
    private final FileManager fileManager = new FileManager();
    /**
     * 文件列表
     */
    public ListView<FileListModel> fileListView = new ListView<>();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        mainPane.widthProperty().addListener((observable, oldValue, newValue) -> {
            showPane.setPrefWidth(mainPane.getWidth() - toolBar.getWidth());
            downloadListView.setPrefWidth(mainPane.getWidth());
        });

        mainPane.heightProperty().addListener((observable, oldValue, newValue) -> {
            toolBar.setPrefHeight(mainPane.getHeight());
            downloadListView.setPrefHeight(mainPane.getHeight());
        });
        ObservableList<DownloadViewModel> downloadViewModels = FXCollections.observableArrayList();
        for (int i = 0; i < 10; i++) {
            DownloadViewModel model = new DownloadViewModel();
            model.setDoubleProperty(0);
            model.setDownloadName("下载名称" + i);
            downloadViewModels.add(model);
        }
        downloadListView.setItems(downloadViewModels);
        //设置下载列表的cell，进度条长度为mainPane减去100
        downloadListView.setCellFactory(View.newInstance(mainPane.widthProperty().subtract(200)));
    }

    /**
     * 打开设置页面
     *
     * @param actionEvent
     */
    public void openSetView(ActionEvent actionEvent) {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/dialogue/set-view.fxml"));
        try {
            Scene scene = new Scene(fxmlLoader.load());
            Stage newStage = new Stage();
            //设置设置图标
            Image icon = new Image(Objects.requireNonNull(getClass().getResourceAsStream("/image/设置.png")));
            newStage.getIcons().add(icon);
            newStage.setTitle("设置");
            newStage.initModality(Modality.APPLICATION_MODAL);
            newStage.setResizable(false);
            newStage.setScene(scene);
            newStage.centerOnScreen();
            newStage.show();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 展示视频播放页面
     *
     * @param mouseEvent
     */
    public void showVideoPlay(MouseEvent mouseEvent) throws IOException {
        System.out.println("点击替换");
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/play-video-view.fxml"));
        fxmlLoader.load();
        PlayVideoController controller = fxmlLoader.getController();
        //允许改变窗口大小
        showPane.getChildren().clear();
        showPane.getChildren().add(controller.mainPane);
    }

    /**
     * 展示下载页面
     *
     * @param mouseEvent
     */
    public void showDownload(MouseEvent mouseEvent) {
        downloadListView.getItems().clear();
        System.out.println(showPane.getWidth());

        ObservableList<DownloadViewModel> downloadViewModels = FXCollections.observableArrayList();
        for (int i = 0; i < 10; i++) {
            DownloadViewModel model = new DownloadViewModel();
            model.setDoubleProperty(0);
            model.setDownloadName("下载名称" + i);
            downloadViewModels.add(model);
        }
        downloadListView.setItems(downloadViewModels);

        showPane.getChildren().clear();
        showPane.getChildren().add(downloadListView);
    }

    /**
     * 选择上传文件
     *
     * @param actionEvent
     */
    public void openFile(ActionEvent actionEvent) {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择一个或多个文件");
        Stage stage = new Stage();
        List<File> files = fileChooser.showOpenMultipleDialog(stage);
        if (files.isEmpty()) {
            return;
        }
        for (File selectedFile : files) {
            Thread start = Thread.ofVirtual().start(() -> {
                try {
                    fileManager.uploadFile(selectedFile);
                } catch (NoSuchAlgorithmException e) {
                    System.out.println(selectedFile.getAbsolutePath() + "上传异常....");
                }
            });
        }
    }

    /**
     * 打开文件查询列表
     *
     * @param actionEvent
     */
    public void openFileList(ActionEvent actionEvent) {
        fileListView.getItems().clear();
        List<FileListModel> fileListModels = fileManager.queryFilePage(1L, 10L);
        ObservableList<FileListModel> fileObservableList = FXCollections.observableArrayList(fileListModels);
        fileListView.setItems(fileObservableList);
        //设置下载列表的cell，进度条长度为mainPane减去100
        fileListView.setCellFactory(new Callback<ListView<FileListModel>, ListCell<FileListModel>>() {
            @Override
            public ListCell<FileListModel> call(ListView<FileListModel> fileList) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(FileListModel item, boolean empty) {
                        super.updateItem(item, empty);
                        if (!empty) {
                            //展示项
                            BorderPane borderPane = new BorderPane();
                            borderPane.getStylesheets().add("css/controller/main-controller.css");
                            borderPane.getStyleClass().add("list-view-download-vbox-hbox");

                            HBox hBox = new HBox();
                            hBox.setAlignment(Pos.CENTER_LEFT);
                            ImageView view = new ImageView("image/video.ico");
                            view.setPreserveRatio(true);
                            view.setFitHeight(30);
                            Tile tile = new Tile(item.getFileName(), item.getFileMd5());


                            Button add = new Button(null, new FontIcon(AntDesignIconsOutlined.DOWNLOAD));
                            Button del = new Button(null, new FontIcon(AntDesignIconsOutlined.DELETE));

                            // 在事件处理中确保在JavaFX Application Thread上执行
                            del.setOnMouseClicked(event -> Platform.runLater(() -> {
                                Map<String, String> params = new HashMap<>();
                                params.put("fileId", String.valueOf(item.getId()));
                                Boolean deleteResult = RequestComponent.get("/operation_file/delete_by_file", Boolean.class, params);
                                if (deleteResult) {
                                    fileList.getItems().remove(item);
                                }
                            }));

                            RingProgressIndicator progressIndicator = new RingProgressIndicator(0, false);
                            progressIndicator.setMinSize(40, 40);
                            add.setOnMouseClicked(event -> Platform.runLater(() -> {

                            }));


                            HBox box = new HBox(20, progressIndicator, add, del);
                            box.setAlignment(Pos.CENTER_RIGHT);
                            box.setPadding(new Insets(0, 100, 0, 0));
                            this.setOnMouseEntered(event -> this.setStyle(StyleConstant.LIST_VIEW_STYLE_EXITED));
                            hBox.getChildren().addAll(view, tile);
                            borderPane.setLeft(hBox);
                            borderPane.setRight(box);
                            borderPane.prefWidthProperty().bind(mainPane.widthProperty());

                            VBox vBox = new VBox();
                            //使用main的css
                            vBox.getStylesheets().add("css/controller/main-controller.css");
                            vBox.getStyleClass().add("list-view-download-vbox");
                            vBox.getChildren().add(borderPane);
                            setGraphic(borderPane);
                        } else {
                            setGraphic(null);
                            setText(null);
                        }
                    }
                };
            }
        });
        fileListView.prefWidthProperty().bind(mainPane.widthProperty());
        fileListView.prefHeightProperty().bind(mainPane.heightProperty());
        showPane.getChildren().clear();
        showPane.getChildren().add(fileListView);
    }

    /**
     * h5上传
     *
     * @param actionEvent
     */
    public void h5Upload(ActionEvent actionEvent) {
        ImageView view = new ImageView();

        // 获取本地主机的InetAddress对象
        Config config = Config.global().get("server.port");
        SysConfigService sysConfigService = new SysConfigServiceImpl();
        //先查询出库内数据
        Sysconfig sysconfig = sysConfigService.selectByTag(SystemConstant.LOCAL_AREA_NETWORK);

        String uploadUrl = StringConstant.HTTP + sysconfig.getValue() +
                StringConstant.PROFANITY + config.asInt().get() + "/static/h5Upload.html";
        Image image = QRCodeGenerator.generateQRCode(uploadUrl);
        view.setImage(image);

        ListView<String> ipListView = new ListView<>(FXCollections.observableArrayList(IPUtil.getIPs()));
        ipListView.prefHeightProperty().bind(showPane.heightProperty());

        ipListView.setCellFactory(new Callback<>() {
            @Override
            public ListCell<String> call(ListView<String> param) {
                return new ListCell<>() {
                    @Override
                    protected void updateItem(String item, boolean empty) {
                        super.updateItem(item, empty);
                        if (!empty) {
                            BorderPane borderPane = new BorderPane();
                            Button button = new Button("设为默认地址");
                            button.prefHeightProperty().bind(ipListView.heightProperty());
                            button.setOnMouseClicked(event -> {
                                Sysconfig updateConfig = new Sysconfig();
                                updateConfig.setValue(item);
                                sysConfigService.updateByTag(SystemConstant.LOCAL_AREA_NETWORK, updateConfig);
                                String url = StringConstant.HTTP + item +
                                        StringConstant.PROFANITY + config.asInt().get()
                                        + "/static/h5Upload.html";
                                view.setImage(QRCodeGenerator.generateQRCode(url));
                            });
                            Text textField = new Text(item);
                            if (sysconfig.getValue().equals(item)) {
                                textField.setFill(Color.rgb(103, 94, 232));
                            }
                            InputGroup inputGroup = new InputGroup(textField, button);
                            inputGroup.setAlignment(Pos.CENTER_RIGHT);
                            borderPane.setLeft(inputGroup);
                            borderPane.setRight(button);
                            setGraphic(borderPane);
                        } else {
                            setGraphic(null);
                            setText(null);
                        }
                    }
                };
            }
        });
        Text text = new Text("需要在同一个网络段下才能扫码上传");
        VBox vBox = new VBox(text, view);
        vBox.setAlignment(Pos.CENTER);
        vBox.prefWidthProperty().bind(showPane.widthProperty().subtract(ipListView.widthProperty()));


        HBox hBox = new HBox(ipListView, vBox);
        hBox.prefWidthProperty().bind(showPane.widthProperty());
        showPane.getChildren().clear();
        showPane.getChildren().addAll(hBox);
    }
}
